package Mysql;

import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class MySQL {
	
	private String host;
	private int port;
	private String user;
	private String password;
	private String database;

	private Connection conn;
	public MySQL() throws Exception  {
		File file = new File("plugins/Projekt", "config.yml");
		FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
		
		String db = "database.";
		this.host = cfg.getString(db + "host");
		this.port = cfg.getInt(db + "port");
		this.user = cfg.getString(db + "user");		
		this.password = cfg.getString(db+ "password");//.substring(1, cfg.getString(db+ "password").length() - 1);
		if (this.password == null){
			this.password = "";
		}
		this.database = cfg.getString(db + "database");
		this.openConnection();
	}
	
	public void queryUpdate(String query){
		Connection conn = this.conn;
		PreparedStatement st =  null;
		try {
			st = conn.prepareStatement(query);
			st.executeUpdate();
		} catch (SQLException e) {
			System.out.println("Failed to send Update '" + query + "'.");
		}finally{
			this.closeResources(null, st);
		}
	}
	
	public Connection openConnection() throws Exception {
			Class.forName("com.mysql.jdbc.Driver");	
			Connection conn = DriverManager.getConnection("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database, this.user, this.password);
			this.conn = conn;
			return conn;
	}
	
	public Connection getConnection(){
		return this.conn;
	}
	
	public boolean hasConnection(){
		try {
			return this.conn != null || this.conn.isValid(1);
		} catch (SQLException e) {
			return false;
		}
	}
	
	public void closeResources(ResultSet rs, PreparedStatement st){
		if (rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
			}
		}
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
			}
		}
	}
	
	public void closeConnection(){
		try {
			this.conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{this.conn = null;
	
		}

	}

}